import request from '@/utils/request'
import store from '@/store'

// 请求首页所有的频道
export function getAllChannels () {
  return request({
    url: 'channels'
  })
}

// 获取个人订阅频道
// 数据的处理放入api/home.js
export async function getMyChannels () {
  const token = store.state.user.token
  if (!token) {
    const myChannels = window.localStorage.getItem('mychannels')
    if (myChannels) {
      return JSON.parse(myChannels || '[]')
    } else {
      const [err, data] = await request({
        url: 'user/channels'
      })
      if (err) return this.$toast.fail(err)
      //  存储数据
      window.localStorage.setItem('mychannels', JSON.stringify(data.data.data.channels))
      // 在返回之前进行存储
      return data.data.data.channels
    }
  }
  const [err, data] = await request({
    url: 'user/channels'
  })
  if (err) return this.$toast.fail(err)

  // 在返回之前进行存储
  return data.data.data.channels
}

// 添加个人频道
export function addChannel (myChannels) {
  console.log('==========', myChannels)
  const token = store.state.user.token
  if (!token) {
    // 1.获取本地存储的mychannels
    const localChannels = JSON.parse(window.localStorage.getItem('mychannels'))
    // 2.拼接出来一个对象 {id, name} 添加到数组
    const { id, name } = myChannels[myChannels.length - 1]
    localChannels.push({
      id,
      name
    })
    // 3.将数组重新存储到本地存储
    window.localStorage.setItem('mychannels', JSON.stringify(localChannels))
    return Promise.resolve('ok')
  } else {
    return request({
      url: 'user/channels',
      method: 'PUT',
      data: {
        channels: myChannels
      }
    })
  }
}

export function deleteChannel (id) {
  const token = store.state.user.token
  if (!token) {
    let mychannels = JSON.parse(window.localStorage.getItem('mychannels') || '[]')
    mychannels = mychannels.filter((item) => {
      return item.id !== id
    })

    // 一定要将数据转化成字符串，才可以存储到本地存储中去。
    window.localStorage.setItem('mychannels', JSON.stringify(mychannels))
  } else {
    return request({
      url: 'user/channels/' + id,
      method: 'DELETE'
    })
  }
}

// 获取频道下的文章列表？
/* eslint-disable */
export function getArticleListByCID (channel_id, timestamp) {
  return request({
    url: 'articles',
    params: {
      channel_id,
      timestamp
    }
  })
}
